<?php
namespace app\common\logic;

use app\common\exception\FailException;
use app\common\model\User as UserModel;
use app\common\model\Shop as ShopModel;
use fast\Random;
use think\Controller;
use think\Db;
use think\Exception;

class Pay extends Controller
{
   public function pay($userid,$shopid,$money,$type){
      $userinfo=UserModel::where("id",$userid)->where("status",1)->find();
      $money=abs($money);
      if(!$userinfo) {
           throw new FailException(['code' => 201,"msg"=>"用户不存在","errorCode"=>300]);
           die();
      }
      //计算税费
      $new_tax_fl=Db::table("t_config")->where("name","new_tax")->value("data");
      $tax_money=  floor($new_tax_fl*$money*100)/100;

      //计算服务费
      $new_service_fl=Db::table("t_config")->where("name","new_service")->value("data");
      $service_money=  floor($new_service_fl*$money*100)/100;

      //合计
      $total_money=$money+$tax_money+$service_money;

      $shop = ShopModel::where("id",$shopid)->where("status",1)->find();

      if(!$shop){
          throw new FailException( ['code' => 201,"msg"=>"商家正在维护暂不能支付，请联系客服","errorCode"=>404]);

      }


       Db::startTrans();    //开启事务
       try{
           $usercapital=Db::table("t_capital")->where("uid",$userid)->where("type",2)->where("status",1)->lock(true)->find();
           if($type==1){
               if((float)$usercapital['money']<=(float)$total_money){

                   throw new FailException( ['code' => 201,"msg"=>"用户资金不足","errorCode"=>300]);
               }
           }
           $shopcapital=Db::table("t_capital")->where("uid",$shopid)->where("type",1)->where("status",1)->lock(true)->find();

           $total_money=abs($total_money);
           $zf_total_money=0-$total_money;

           $usercapital_log="账号：".$userinfo['username']." 向 ".$shop['name']." 支付了 ".$total_money."元,其中税费".$tax_money."元,服务费".$service_money."元";
           $usercapital_log2="账号：".$userinfo['username']." 向 ".$shop['name']." 支付了现金 ".$total_money."元,其中税费".$tax_money."元,服务费".$service_money."元";

           $sbz=$shop['name']." 收入 ".$money;

           $usermoney=$usercapital['money']-$total_money;

           $shopmoney=$shopcapital['money']+$money;

           $order_add_info = [
               'tel'=>$userinfo['mobile'],
               'user_id' => $userid,
               'shop_id' => $shopid,
               'sn'=>Random::build("nozero",16),
               'area_id' => $shop['area_id'],
               'address'=>$shop['address'],
               'real_price'=>abs($money),
               'total_price'=>abs($total_money),
               'tax_price'=>$tax_money,
               'service_price'=>$service_money,
               'status'=>1,
               'created_at'=>date("Y-m-d H:i:s",time()),
               'updated_at'=>date("Y-m-d H:i:s",time()),
               'type'=>$type
           ];

           $orderid=Db::table('t_order')->insertGetId($order_add_info);
            
          if($type==1){   //余额支付
             $usercapital_water_data = [
                 'cid'=>$usercapital['id'],
                 'uid' => $userid,
                 'shopid'=>$shopid,
                 'money' => $zf_total_money,
                 'type'=>1,
                 'addtime'=>time(),
                 'name'=>$usercapital_log,
                 'order_id'=>$orderid
             ];

             Db::table('t_capital_water')->insertGetId($usercapital_water_data);

             Db::table('t_capital')->where('uid',$userid) ->where("type",2)->where("status",1)->update([
               'money'=>$usermoney,
               'consumer'=>$usercapital['consumer']+$total_money
             ]);
           }elseif($type==2){ //现金支付
            
             $usercapital_water_data = [
                 'cid'=>$usercapital['id'],
                 'uid' => $userid,
                 'shopid'=>$shopid,
                 'money' => $zf_total_money,
                 'type'=>6,
                 'addtime'=>time(),
                 'name'=>$usercapital_log2,
                 'order_id'=>$orderid
             ];
             Db::table('t_capital_water')->insertGetId($usercapital_water_data);

           }else{
              throw new FailException( ['code' => 201,"msg"=>"该支付方式正在维护中","errorCode"=>300]);
          }
           //创建订单


           //商家获取金额
           $shopcapital_water_data = [
               'cid'=>$shopcapital['id'],
               'uid' => $userid,
               'shopid'=>$shopid,
               'money' => $zf_total_money,
               'type'=>2,
               'addtime'=>time(),
               'name'=>$sbz,
               'order_id'=>$orderid
           ];
           Db::table('t_capital_water')->insertGetId($shopcapital_water_data);

           Db::table('t_capital')->where('uid',$shopid) ->where("type",1)->where("status",1)->update([
              'money'=>$shopmoney,
           ]);

//               //推荐人分红利率
//               $referee_fh=Db::table("t_config")->where("name","referee_fh")->value("data");
//
//               $referee_id=Db::table("t_user")->where("id",$userid)->value("referee_id");
//               //如果存在推荐人
//               if($referee_id) {
//
//                   $referee_data = Db::table('t_capital')->where("uid", $referee_id)->lock(true)->find();
//                   if($referee_data) {
//                       $referee_money = floor($money * $referee_fh * 100) / 100;
//
//                       $referee_desc = "账号：".$userinfo['username'] . " 消费了 " . $money . "元,获取推荐人奖励" . $referee_money . "元";
//
//                       $refereecapital_water_data = [
//                           'cid' => $referee_data['id'],
//                           'uid' => $userid,
//                           'shopid' => $shopid,
//                           'money' => $referee_money,
//                           'type' => 9,
//                           'addtime' => time(),
//                           'name' => $referee_desc
//                       ];
//                       Db::table('t_capital_water')->insertGetId($refereecapital_water_data);
//
//                       Db::table('t_capital')->where('uid', $referee_id)->where("type", 2)->where("status", 1)->update([
//                           'money' => $referee_data['money'] + $referee_money,
//                           'consumer'=>$referee_data['consumer']+$total_money
//                       ]);
//                   }
//               }
//
//               //代理商分红利率
//               $agent_fh=Db::table("t_config")->where("name","agent_fh")->value("data");
//
//               $agent_id=Db::table("t_user")->where("id",$userid)->value("agent_id");
//
//               if($agent_id) {
//                   $agent_data = Db::table('t_agent')->where("id", $agent_id)->where("status", 1)->lock(true)->find();
//                   if($agent_data){
//                       $agent_money = floor($money*$agent_fh*100)/100;
//                       $agent_desc = "账号：".$userinfo['username'] ." 消费了 " . $money . "元,获取代理奖励" . $agent_money . "元";
//                       $agent_log_data = [
//                           'buid' => $userid,
//                           'aid' => $agent_id,
//                           'money' => $agent_money,
//                           'addtime' => time(),
//                           'desc' => $agent_desc
//                       ];
//                       Db::table('t_agent_log')->insertGetId($agent_log_data);
//
//                       Db::table('t_agent')->where('id', $agent_id)->where("status", 1)->update([
//                           'money' => $agent_data['money'] + $agent_money
//
//                       ]);
//
//                   }
//               }


           Db::commit();   //提交事务

       }catch(FailException $e){
           Db::rollback(); //回滚事务
           throw new FailException(['code' => 201,"msg"=>$e->msg,"errorCode"=>405]);
           die();
       }


           $bldata1 = Db::table("t_config")->where("name", "new_fh_gd")->value("data");
           $bldata2 = Db::table("t_config")->where("name", "new_cz_bl")->value("data");
           $re1 = Pay::share_out_bonus($userid, $money, $bldata1, $userid,1,$orderid);
           if ($re1 > 1) {
               Pay::share_out_bonus($re1, $money, $bldata2, $userid,2,$orderid);
           }

       return ["code"=>200,"msg"=>"成功！","data"=>$orderid];

   }

    public function yy_pay_password($userid,$password){

        $userinfo=UserModel::where("id",$userid)->where("status",1)->find();
        if(!$userinfo['pay_password']){

            throw new FailException(["code"=>201,"msg"=>"支付密码未设置","errorCode"=>432]);
        }
        if(!$userinfo) {
            return false;
        }else{
            if($password!=$userinfo['pay_password']){
                return false;
            }else{
                return true;
            }
        }



    }
  
    public static function share_out_bonus($uid,$money,$bldata1,$yuid,$level,$orderid){
        Db::startTrans();    //开启事务
        try{
            $pid = Db::table("t_user")->where("id",$uid)->value("pid");
            if($pid){

                $username = Db::table("t_user")->where("id",$yuid)->value("username");
                $refereedata = Db::table("t_user")->where("id",$pid)->find();

                if(!$refereedata){

                    Db::table("t_overflow_log")->insert([
                        "uid"=>$pid,
                        "money"=>$money*$bldata1,
                        "addtime"=>time(),
                        'created_at'=>date("Y-m-d H:i:s",time()),
                        'updated_at'=>date("Y-m-d H:i:s",time())
                    ]);
                }
                $capitalc=Db::table("t_capital")->where("uid",$pid)->lock(true)->find();

                if($refereedata['status']!=1){

                    Db::table("t_overflow_log")->insert([
                        "uid"=>$pid,
                        "money"=>$money*$bldata1,
                        "addtime"=>time(),
                        'created_at'=>date("Y-m-d H:i:s",time()),
                        'updated_at'=>date("Y-m-d H:i:s",time())
                    ]);

                }
                $cc=$capitalc['count_putmoney']+$money*$bldata1; //获得
                $put_out_money=$capitalc['put_out_money']+$money*$bldata1; //获得
                    if($cc>$capitalc['putmoney'] && $pid!=1){

                        $overmoney= $cc-$capitalc['putmoney'];

                        Db::table("t_overflow_log")->insert([
                            "uid"=>$pid,
                            "money"=>$overmoney,
                            "addtime"=>time(),
                            'created_at'=>date("Y-m-d H:i:s",time()),
                            'updated_at'=>date("Y-m-d H:i:s",time())
                        ]);

                        Db::table("t_capital")->where("uid",$pid)->where("type",2)->update([
                            "count_putmoney"=>$capitalc['putmoney'],
                            "put_out_money"=>$put_out_money
                        ]);
                        Db::table("t_capital_water")->insert([
                            "uid"=>$pid,
                            "type"=>8,
                            "cid"=>$capitalc['id'],
                            "name"=>"用户".$username."消费分成".($money*$bldata1)."收入".abs($capitalc['putmoney']-$capitalc['count_putmoney'])."其中溢出".$overmoney,
                            "money"=> abs($capitalc['putmoney']-$capitalc['count_putmoney']),
                            "addtime"=>time(),
                            "b_username"=>$username,
                            "level"=>$level,
                            "b_money"=>$money,
                            "order_id"=>$orderid
                        ]);

                    }else{

                        Db::table("t_capital")->where("uid",$pid)->where("type",2)->update([
                            "count_putmoney"=>$capitalc['count_putmoney']+$money*$bldata1,
                            "put_out_money"=>$put_out_money
                        ]);
                        Db::table("t_capital_water")->insert([
                            "uid"=>$pid,
                            "type"=>8,
                            "cid"=>$capitalc['id'],
                            "name"=>"用户".$username."消费分成".$money*$bldata1,
                            "money"=> $money*$bldata1,
                            "addtime"=>time(),
                            "b_username"=>$username,
                            "level"=>$level,
                            "b_money"=>$money,
                            "order_id"=>$orderid
                        ]);

                    }
                Db::commit();
                return $pid;
            }else{
                return 0;
            }

        }catch (Exception $e){
            Db::rollback(); //回滚事务
            throw new FailException(['code' => 201,"msg"=>"返利失败","errorCode"=>406]);
            die();
        }


    }
}